<!-- 判断题库 -->
<template>
    <div>
        <!-- 第一部分 -->
        <el-row class="Header">
            <el-col :span="12">
                <div>
                    <el-input placeholder="请输入题目编号 J-xxx" v-model="params.questionNumber" clearable>
                        <el-select v-model="params.chapter" slot="prepend" placeholder="请选择">
                            <el-option v-for="(item,index) in chapters" :key="index"
                                :label="item.chapterNumber+item.description" :value="item.id"></el-option>
                        </el-select>
                        <el-button slot="append" icon="el-icon-search" @click="getJudgeQuestionlist"></el-button>
                    </el-input>
                </div>
            </el-col>

            <el-col :span="12">
                <div class="addChooseButton">
                    <el-button type="primary" @click="addJudgeQuestionFold=true">添加判断题</el-button>
                </div>
            </el-col>
        </el-row>

        <!-- 添加题目对话框 -->
        <el-dialog title="添加题目" :visible.sync="addJudgeQuestionFold" width="50%" :before-close="handleClose">
            <!-- form 表单 -->
            <el-form :model="addQuestionparam" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                <!-- 题目编号 -->
                <el-form-item label="题目编号" prop="questionNumber">
                    <el-input placeholder="请输入题目编号  J-xxx" v-model="addQuestionparam.questionNumber"></el-input>
                </el-form-item>
                <!-- 章节选择 -->
                <el-form-item label="章节选择" prop="chapter">
                    <el-select v-model="addQuestionparam.chapter" placeholder="请选择章节">
                        <el-option v-for="(item,index) in chapters" :key="index"
                            :label="item.chapterNumber+item.description" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <!-- 题目描述 -->
                <el-form-item label="题目描述" prop="description">
                    <el-input autosize type="textarea" maxlength="255" v-model="addQuestionparam.description"></el-input>
                </el-form-item>
                <el-form-item label="答案选择" prop="answer">
                    <el-select v-model="addQuestionparam.answer" placeholder="请选择答案">
                        <el-option v-for="(item,index) in answers" :key="index" :label="item.name" :value="item.value"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="resetForm">重置</el-button>
                <el-button type="primary" @click="addQuestion">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 第二部分，表格部分 -->
        <el-table :data="tableData" style="width: 100%">
            <el-table-column type="index" label="序号" width="100"></el-table-column>
            <el-table-column label="章节" width="100">
                <template slot-scope="scoped">
                    <span>第{{scoped.row.chapter}}章</span>
                </template>
            </el-table-column>
            <el-table-column label="题目编号" prop="questionNumber" width="100"></el-table-column>
            <el-table-column label="题目描述" prop="description"></el-table-column>
            <el-table-column label="答案" width="100">
                <template slot-scope="scope">
                    <span v-if="scope.row.answer === 0" class="el-icon-circle-close">错误</span>
                    <span v-if="scope.row.answer === 1" class="el-icon-circle-check">正确</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="140">
                <template slot-scope="scoped">
                    <el-button type="primary" icon="el-icon-edit" circle @click="editJudge(scoped.row.id)"></el-button>
                    <el-button type="danger" icon="el-icon-delete" circle @click="delectJudge(scoped.row.id)"></el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 修改选择题对话框 -->
        <el-dialog title="修改题目" :visible.sync="UpdateJudgeQuestionFold" width="50%" :before-close="UpdatehandleClose">
            <!-- form 表单 -->
            <el-form :model="UpdateJudgeparam" :rules="rules" ref="UpdateruleForm" label-width="100px"
                class="demo-ruleForm">
                <!-- 题目编号 -->
                <el-form-item label="题目编号">
                    <el-input disabled v-model="UpdateJudgeparam.questionNumber"></el-input>
                </el-form-item>
                <!-- 章节选择 -->
                <el-form-item label="章节选择" prop="chapter">
                    <el-select v-model="UpdateJudgeparam.chapter" placeholder="请选择章节">
                        <el-option v-for="(item,index) in chapters" :key="index"
                            :label="item.chapterNumber+item.description" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <!-- 题目描述 -->
                <el-form-item label="题目描述" prop="description">
                    <el-input autosize type="textarea" maxlength="255" v-model="UpdateJudgeparam.description"></el-input>
                </el-form-item>
                <el-form-item label="答案选择" prop="answer">
                    <el-select v-model="UpdateJudgeparam.answer" placeholder="请选择答案">
                        <el-option v-for="(item,index) in answers" :key="index" :label="item.name" :value="item.value"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="UpdateresetForm">重 置</el-button>
                <el-button type="primary" @click="UpdateQuestion">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 分页查询 -->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="params.currentPage" :page-sizes="[5, 8, 10]" :page-size="params.pageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
    </div>
</template>

<script>
    export default {
        watch: {
            'params.chapter': { // 监视params对象中的 chapter 章节id 属性变化  
                handler(newVal) {
                    // TODO 注意，这里的这个 questionNumber 清空之后还要再发一次请求。后面再处理
                    this.params.questionNumber = ""
                    // 因为  params.chapter 发生变化 这里就会自动发送一次请求
                    this.getJudgeQuestionlist()
                },
            },
            'params.questionNumber': { // 监视param对象中的 questionNumber 属性是否为空 
                handler(newVal) {
                    if (newVal === null || newVal === "") {
                        this.getJudgeQuestionlist()
                    }
                },
            },
        },

        created() {
            this.getChapter()
            this.getJudgeQuestionlist()
        },
        data() {
            // 判断编码是否重复
            var cf = (value) => {
                for (let i = 0; i < this.tableData.length; i++) {
                    if (value === this.tableData[i].questionNumber) {
                        return true
                    }
                }
                return false
            }
            // 编号表单验证
            var questionNumberRule = (rule, value, callback) => {
                var regex = /^J-[A-F0-9][0-9]{2,}$/;
                if (!value) {
                    return callback(new Error('请输入编号'));
                } else if (!regex.test(value)) {
                    return callback(new Error('编码格式不满足'));
                } else if (cf(value)) {
                    callback(new Error('编码已经存在'));
                } else {
                    callback();
                }
            };
            return {
                // 章节信息
                chapters: [],
                // 分页查询请求参数
                params: {
                    questionNumber: "",      // 搜索框内容，表示题目编号
                    chapter: 1,             // 章节id
                    currentPage: 1,         // 页数
                    pageSize: 5             // 每页记录数
                },
                // 表格数据
                tableData: [],
                // 表格数据总数
                total: 0,
                // 添加题目数据
                addQuestionparam:{
                    questionNumber:"",      // 题目编号
                    chapter:null,           // 题目章节id
                    description:"",         // 题目描述
                    answer:null              // 答案
                },
                // 修改题目数据
                UpdateJudgeparam:{
                    id:null,                // 题目id
                    questionNumber:"",      // 题目编号
                    chapter:null,           // 题目章节id
                    description:"",         // 题目描述
                    answer:null              // 答案
                },
                // 答案01的选择
                answers:[
                    {name:"正确",value:1},
                    {name:"错误",value:0},
                ],
                // 表单验证
                rules: {
                    questionNumber: [
                        { validator: questionNumberRule, trigger: 'blur' }
                    ],
                    description: [
                        { required: true, message: '请输入题目描述', trigger: 'blur' },
                    ],
                    answer: [
                        { required: true, message: '答案不能为空', trigger: 'blur' },
                    ],
                    chapter: [
                        { required: true, message: '请选择章节', trigger: 'blur' },
                    ]
                },
                // 控制对话框的打开与关闭
                addJudgeQuestionFold:false,
                UpdateJudgeQuestionFold:false,
            };
        },
        methods: {
            // 获取章节信息
            async getChapter() {
                const { data: res } = await this.$axios.get("/chapter/getChapter")
                this.chapters = res.data
            },
            // 分页查询，发送请求
            async getJudgeQuestionlist() {
                const { data: res } = await this.$axios.post("/Judge/getJudgeQuestion", this.params)
                this.tableData = res.data.records
                this.total = res.data.total
            },
            // 删除试题
            async delectJudge(id){
                const { data: res } = await this.$axios.delete("/Judge/deleteQuestion", {
                    params: {
                        id: id,//题目id
                    }
                })
                if (res.code == 200) {
                    this.getJudgeQuestionlist()
                    return this.$message.success("删除成功")
                }
                if (res.code == 512) {
                    return this.$message.error("此题目关联了试卷，不能删除")
                }else{
                    return this.$message.error("网络错误")
                }
            },

            // 分页查询数据发生变化
            handleSizeChange(newPageSize) {
                this.params.pageSize = newPageSize
                this.getJudgeQuestionlist()
            },
            handleCurrentChange(newCurrent) {
                this.params.currentPage = newCurrent
                this.getJudgeQuestionlist()
            },

            // 添加题目对话框关闭前的操作
            handleClose() {
                this.resetForm()
                this.addJudgeQuestionFold = false
            },
            // 重置添加题目
            resetForm() {
                this.$refs.ruleForm.resetFields();
            },
            // 添加题目
            addQuestion() {
                this.$refs.ruleForm.validate(async valid => {
                    if (!valid) return this.$message.error("请完善表格")
                    const { data: res } = await this.$axios.post('/Judge/addQuestion', this.addQuestionparam)
                    if (res.code === 200) {
                        this.getJudgeQuestionlist()
                        this.handleClose()
                        return this.$message.success("添加成功")
                    } else if (res.code === 511) {
                        return this.$message.error("编码重复")
                    } else {
                        return this.$message.error("你输入的信息有误")
                    }
                })
            },
            // 修改题目打开口， 需要当行数据的id
            editJudge(id) {
                this.UpdateJudgeparam.id = id
                this.UpdateJudgeQuestionFold = true
                var data = this.tableData.find(item => item.id === id)
                this.UpdateJudgeparam.questionNumber = data.questionNumber
                this.UpdateJudgeparam.chapter = data.chapter
                this.UpdateJudgeparam.description = data.description
                this.UpdateJudgeparam.answer = data.answer
            },
            // 修改题目对话框关闭前的操作
            UpdatehandleClose() {
                this.UpdateresetForm()
                this.UpdateJudgeQuestionFold = false
            },
            // 重置修改题目的表单数据
            UpdateresetForm() {
                this.$refs.UpdateruleForm.resetFields();
            },
            // 发送请求，更改数据。
            UpdateQuestion() {
                this.$refs.UpdateruleForm.validate(async valid => {
                    if (!valid) return this.$message.error("请完善表格")
                    const { data: res } = await this.$axios.post('/Judge/updateQuestion', this.UpdateJudgeparam)
                    if (res.code === 200) {
                        this.getJudgeQuestionlist()
                        this.UpdatehandleClose()
                        return this.$message.success("修改成功")
                    } else if (res.code === 512) {
                        return this.$message.error("不能修改答案，该试题已经关联试卷")
                    }else {
                        return this.$message.error("网络错误")
                    }
                })
            },
        }
    }
</script>

<style lang="less" scoped>
    /* 头部样式 */
    .Header {
        margin-bottom: 15px;

        /* 选择框 */
        .el-select {
            width: 300px;
        }

        /* 添加题目按钮 */
        .addChooseButton {
            text-align: right;

            .el-button {
                margin-right: 50px;
            }
        }
    }
</style>